// pages/user-setting/user-setting.js
const app = getApp()

Page({
  data: {
    name: '',
    gender: 'male',
    age: '',
    height: '',
    weight: '',
    bloodSugar: '',
    uricAcid: '',
    systolicPressure: '',
    diastolicPressure: '',
    allergies: '',
    otherRestrictions: '',
    
    genderOptions: [
      { label: '男', value: 'male' },
      { label: '女', value: 'female' }
    ],
    
    dietPreferences: [
      { label: '低盐', value: 'low_salt', checked: false },
      { label: '低脂', value: 'low_fat', checked: false },
      { label: '低糖', value: 'low_sugar', checked: false },
      { label: '低嘌呤', value: 'low_purine', checked: false },
      { label: '素食', value: 'vegetarian', checked: false }
    ],
    
    showHealthAssessment: false,
    bmi: '',
    bmiStatus: '',
    bmiText: '',
    bloodSugarStatus: '',
    bloodSugarText: '',
    uricAcidStatus: '',
    uricAcidText: ''
  },

  onLoad(options) {
    this.loadUserData()
  },

  loadUserData() {
    const healthInfo = wx.getStorageSync('healthInfo')
    if (healthInfo) {
      this.setData({
        name: healthInfo.name || '',
        gender: healthInfo.gender || 'male',
        age: healthInfo.age || '',
        height: healthInfo.height || '',
        weight: healthInfo.weight || '',
        bloodSugar: healthInfo.bloodSugar || '',
        uricAcid: healthInfo.uricAcid || '',
        systolicPressure: healthInfo.systolicPressure || '',
        diastolicPressure: healthInfo.diastolicPressure || '',
        allergies: healthInfo.allergies || '',
        otherRestrictions: healthInfo.otherRestrictions || ''
      })
      
      // 更新饮食偏好
      if (healthInfo.dietPreferences) {
        const updatedPreferences = this.data.dietPreferences.map(pref => ({
          ...pref,
          checked: healthInfo.dietPreferences.includes(pref.value)
        }))
        this.setData({ dietPreferences: updatedPreferences })
      }
      
      this.calculateHealthAssessment()
    }
  },

  // 输入事件处理
  onNameInput(e) {
    this.setData({ name: e.detail.value })
  },

  onGenderChange(e) {
    this.setData({ gender: e.detail.value })
  },

  onAgeInput(e) {
    this.setData({ age: e.detail.value })
    this.calculateHealthAssessment()
  },

  onHeightInput(e) {
    this.setData({ height: e.detail.value })
    this.calculateHealthAssessment()
  },

  onWeightInput(e) {
    this.setData({ weight: e.detail.value })
    this.calculateHealthAssessment()
  },

  onBloodSugarInput(e) {
    this.setData({ bloodSugar: e.detail.value })
    this.calculateHealthAssessment()
  },

  onUricAcidInput(e) {
    this.setData({ uricAcid: e.detail.value })
    this.calculateHealthAssessment()
  },

  onSystolicInput(e) {
    this.setData({ systolicPressure: e.detail.value })
  },

  onDiastolicInput(e) {
    this.setData({ diastolicPressure: e.detail.value })
  },

  onAllergiesInput(e) {
    this.setData({ allergies: e.detail.value })
  },

  onPreferenceChange(e) {
    const value = e.detail.value
    const updatedPreferences = this.data.dietPreferences.map(pref => ({
      ...pref,
      checked: pref.value === value ? !pref.checked : pref.checked
    }))
    this.setData({ dietPreferences: updatedPreferences })
  },

  onRestrictionsInput(e) {
    this.setData({ otherRestrictions: e.detail.value })
  },

  // 计算健康评估
  calculateHealthAssessment() {
    const { age, height, weight, bloodSugar, uricAcid } = this.data
    
    let bmi = ''
    let bmiStatus = ''
    let bmiText = ''
    
    let bloodSugarStatus = ''
    let bloodSugarText = ''
    
    let uricAcidStatus = ''
    let uricAcidText = ''
    
    // 计算BMI
    if (height && weight) {
      const heightM = height / 100
      bmi = (weight / (heightM * heightM)).toFixed(1)
      
      if (bmi < 18.5) {
        bmiStatus = 'warning'
        bmiText = '偏瘦'
      } else if (bmi >= 18.5 && bmi < 24) {
        bmiStatus = 'normal'
        bmiText = '正常'
      } else if (bmi >= 24 && bmi < 28) {
        bmiStatus = 'warning'
        bmiText = '超重'
      } else {
        bmiStatus = 'danger'
        bmiText = '肥胖'
      }
    }
    
    // 评估血糖
    if (bloodSugar) {
      const sugar = parseFloat(bloodSugar)
      if (sugar < 3.9) {
        bloodSugarStatus = 'danger'
        bloodSugarText = '偏低'
      } else if (sugar >= 3.9 && sugar <= 6.1) {
        bloodSugarStatus = 'normal'
        bloodSugarText = '正常'
      } else if (sugar > 6.1 && sugar <= 7.0) {
        bloodSugarStatus = 'warning'
        bloodSugarText = '偏高'
      } else {
        bloodSugarStatus = 'danger'
        bloodSugarText = '糖尿病'
      }
    }
    
    // 评估尿酸
    if (uricAcid) {
      const acid = parseFloat(uricAcid)
      const isMale = this.data.gender === 'male'
      const normalMax = isMale ? 428 : 357
      const warningMax = isMale ? 480 : 400
      
      if (acid <= normalMax) {
        uricAcidStatus = 'normal'
        uricAcidText = '正常'
      } else if (acid > normalMax && acid <= warningMax) {
        uricAcidStatus = 'warning'
        uricAcidText = '偏高'
      } else {
        uricAcidStatus = 'danger'
        uricAcidText = '高尿酸'
      }
    }
    
    this.setData({
      showHealthAssessment: !!(bmi || bloodSugar || uricAcid),
      bmi,
      bmiStatus,
      bmiText,
      bloodSugarStatus,
      bloodSugarText,
      uricAcidStatus,
      uricAcidText
    })
  },

  // 保存信息
  onSave() {
    const { 
      name, gender, age, height, weight, bloodSugar, uricAcid, 
      systolicPressure, diastolicPressure, allergies, otherRestrictions, dietPreferences 
    } = this.data
    
    // 基本验证
    if (!name) {
      app.showError('请输入姓名')
      return
    }
    
    if (!age || age < 1 || age > 120) {
      app.showError('请输入正确的年龄')
      return
    }
    
    if (!height || height < 50 || height > 250) {
      app.showError('请输入正确的身高')
      return
    }
    
    if (!weight || weight < 10 || weight > 300) {
      app.showError('请输入正确的体重')
      return
    }
    
    // 收集选中的饮食偏好
    const selectedPreferences = dietPreferences
      .filter(pref => pref.checked)
      .map(pref => pref.value)
    
    const healthInfo = {
      name,
      gender,
      age: parseInt(age),
      height: parseFloat(height),
      weight: parseFloat(weight),
      bloodSugar: bloodSugar ? parseFloat(bloodSugar) : null,
      uricAcid: uricAcid ? parseFloat(uricAcid) : null,
      systolicPressure: systolicPressure ? parseInt(systolicPressure) : null,
      diastolicPressure: diastolicPressure ? parseInt(diastolicPressure) : null,
      allergies,
      otherRestrictions,
      dietPreferences: selectedPreferences,
      bmi: this.data.bmi ? parseFloat(this.data.bmi) : null,
      lastUpdate: new Date().toISOString()
    }
    
    app.showLoading('保存中...')
    
    setTimeout(() => {
      wx.setStorageSync('healthInfo', healthInfo)
      
      // 更新用户信息中的健康状态
      const userInfo = wx.getStorageSync('userInfo') || {}
      userInfo.healthStatus = this.getOverallHealthStatus(healthInfo)
      wx.setStorageSync('userInfo', userInfo)
      
      wx.hideLoading()
      app.showSuccess('保存成功')
      
      // 返回上一页或首页
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/index/index'
        })
      }, 1500)
    }, 1000)
  },

  // 获取整体健康状态
  getOverallHealthStatus(healthInfo) {
    if (!healthInfo.bloodSugar && !healthInfo.uricAcid) {
      return '未设置'
    }
    
    let status = '良好'
    if (healthInfo.bloodSugar > 7.0 || healthInfo.uricAcid > 420) {
      status = '需关注'
    }
    if (healthInfo.bloodSugar > 11.1 || healthInfo.uricAcid > 540) {
      status = '需改善'
    }
    
    return status
  },

  // 重置表单
  onReset() {
    wx.showModal({
      title: '确认重置',
      content: '确定要重置所有信息吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            name: '',
            gender: 'male',
            age: '',
            height: '',
            weight: '',
            bloodSugar: '',
            uricAcid: '',
            systolicPressure: '',
            diastolicPressure: '',
            allergies: '',
            otherRestrictions: '',
            dietPreferences: this.data.dietPreferences.map(pref => ({
              ...pref,
              checked: false
            })),
            showHealthAssessment: false
          })
          
          app.showSuccess('重置成功')
        }
      }
    })
  }
})